package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantPropertiesUtil;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("all")
@Controller
@RequestMapping("/api/user/wx")
public class WxController {

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("callback")
    //由微信返回两个值 并调用该方法 code:临时票据 state我们自定义的是当前时间(没啥用)
    public String callback(String code, String state) {
        try {
            //1.获取code
            //2.拿着code和appid去请求微信接口
            //此种方式消耗内存 效率低 易出错
//              String url =
//                "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
//                        ""+ConstantPropertiesUtil.WX_OPEN_APP_ID+
//                        "&secret="+ConstantPropertiesUtil.WX_OPEN_APP_SECRET+"&code="+code+
//                        "&grant_type=authorization_code";
            StringBuffer baseAccessTokenUrl = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                    .append("?appid=%s")
                    .append("&secret=%s")
                    .append("&code=%s")
                    .append("&grant_type=authorization_code");
            //按照顺序拼接参数
            String url = String.format(
                    baseAccessTokenUrl.toString(),
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code);
            //使用httpclient发送get请求 返回值主要包含openid和access_token
            String result = HttpClientUtils.get(url);
            //可转为map或json进行取值
            JSONObject jsonObject = JSONObject.parseObject(result);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //拿着openid和access_token去请求微信的另一个接口,最终得到扫码人的信息
            //判断数据库是否存在openid
            UserInfo userInfo = userInfoService.findUserByOpenid(openid);
            if (userInfo == null) {
                //3 openid和accesstoken再去请求微信接口，得到扫码人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userUrl = String.format(baseUserInfoUrl, access_token, openid);
                String userResult = HttpClientUtils.get(userUrl);
                //获取扫码人昵称
                JSONObject userJson = JSONObject.parseObject(userResult);
                String nickname = userJson.getString("nickname");
                //保存的数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
            //TODO 返回登录需要数据
            //返回name和token字符串
            Map<String,String> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            //使用jwt生成token字符串
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            //判断userInfo是否有手机号，如果手机号为空，返回openid
            //如果手机号不为空，返回openid值是空字符串
            //前端判断：如果openid不为空，绑定手机号，如果openid为空，不需要绑定手机号
            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            //跳转到前端页面
            return "redirect:http://localhost:3000/weixin/callback?" +
                    "token="+ map.get("token")+
                    "&openid="+map.get("openid")+
                    "&name="+URLEncoder.encode(map.get("name"),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    //返回登录二维码参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public R getLoginParam() {
        try {
            Map<String, Object> map = new HashMap<>();
            //appid
            map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
            //scope 官方约定值是snsapi_login
            map.put("scope", "snsapi_login");
            //redirectUri url编码  扫码完成执行的回调函数
            String redirectUri = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
            redirectUri = URLEncoder.encode(redirectUri, "utf-8");
            map.put("redirectUri", redirectUri);

            //可选值 原样输出
            map.put("state", System.currentTimeMillis() + "");
            return R.ok().data(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return R.error();
        }
    }
}
